package org.rslai.tcedit.dao.hibernate;

import java.util.List;
import org.rslai.tcedit.dao.VersionDao;
import org.rslai.tcedit.domain.Page;
import org.rslai.tcedit.domain.Version;
import org.rslai.tcedit.exception.ApplicationException;

/**
 * VersionDao 的实现类
 * 
 * @author rslai
 * 
 * @spring.bean id="versionDao"
 */
public class VersionImpl extends GenericHibernateDao<Version> implements VersionDao {

	public VersionImpl() {
		super(Version.class);
	}

	/**
	 * 创建一个 Version 信息。覆盖 GenericHibernateDao 中的 create 方法。
	 * 
	 * @param version Version对象
	 */
	public void create(Version version) {
		Version tmpVersion = (Version) queryForObject(
				"from Version as a where a.product.id=? and a.name=?",
				new Object[] { version.getProduct().getId(), version.getName() }
		);
		if (tmpVersion != null) {
			throw new ApplicationException("您输入的“版本名”已存在，请重新输入。");
		}

		hibernateTemplate.save(version);
	}
	
	/**
	 * 更新一个 Version 信息。覆盖 GenericHibernateDao 中的 update 方法。
	 * 
	 * @param version Version 对象
	 */
	public void update(Version version) {
		Version tmpVersion = (Version) queryForObject(
				"from Version as a where a.product.id=? and a.name=? and a.id!=?",
				new Object[] { version.getProduct().getId(), version.getName(), version.getId() }
		);
		if (tmpVersion != null) {
			throw new ApplicationException("您输入的“版本名”已存在，请重新输入。");
		}

		hibernateTemplate.update(version);
	}
	private static final String QUERY_VERSION_ASC = "from Version as a order by a.name";
	private static final String QUERY_VERSION_DESC = "from Version as a order by a.name desc";

	@SuppressWarnings("unchecked")
	public List<Version> query(boolean asc) {
		return queryForList(
				asc ? QUERY_VERSION_ASC : QUERY_VERSION_DESC,
				null);
	}

	private static final String QUERY_VERSION_NAME_ASC = "from Version as a where a.product.id=? and a.name LIKE ? order by a.name";
	private static final String QUERY_VERSION_NAME_DESC = "from Version as a where a.product.id=? and a.name LIKE ? order by a.name desc";

	@SuppressWarnings("unchecked")
	public List<Version> query(String productID, Page page, String name, boolean asc) {
		return queryForList(
				"select count(*) from Version as a where a.product.id=? and a.name LIKE ?",
				asc ? QUERY_VERSION_NAME_ASC : QUERY_VERSION_NAME_DESC, 
				new Object[] { productID, name },
				page
		);
	}

}
